/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package thesis.ramstorage.math;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *
 * @author Admin
 * Use 20bit (m = 20)
 */
public class HashFunction {
	private int keySize = 0;
	private MessageDigest md = null;//
	
	public HashFunction(){
		try {
			md = MessageDigest.getInstance("SHA-1");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public HashFunction(int keySize){
		this();
		this.keySize = keySize;
	}
    public int hash(String id){
    	if(keySize == 0){
    		System.out.println("please setup keysize!");
    	}
        return (int) (Math.abs(id.hashCode()) % Math.pow(2, keySize));
    }
    
    public BigInteger generateSHA1(String key) {

		try {
			byte[] hashMsg = md.digest(key.toString().getBytes());
			BigInteger bi = new BigInteger(hashMsg).abs();
			BigInteger mod = new BigInteger( Integer.toString(  (int)Math.pow(2, keySize) ) );
			return bi.mod( mod );
		} catch (Exception e) {
			System.out.println(key + " key ");
			e.printStackTrace();
		}
		return null;
	}
}
